package org.boot.fast.core.api.mapper.provider.impl;

import org.boot.fast.core.api.mapper.provider.DynamicSqlProvider;

import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

import static org.boot.fast.core.api.mapper.provider.DynamicSqlProvider.*;

@SuppressWarnings("unchecked")
public class DynamicQueryProvider {
    public static String buildQuerySql(Map<String, Object> params) {
        String originalSql = (String) params.get("originalSql");
        Map<String, Object> conditionParams = (Map<String, Object>) params.get("params");
        String whereClause = buildWhereClause(conditionParams);
        String orderClause = buildOrderClause(conditionParams);
        String limitClause = buildLimitClause(conditionParams);
        return originalSql + whereClause + orderClause + limitClause;
    }

    public static String buildCountSql(Map<String, Object> params) {
        String originalSql = (String) params.get("originalSql");
        Map<String, Object> conditionParams = (Map<String, Object>) params.get("params");

        String whereClause = buildWhereClause(conditionParams);
        String baseSql = getBaseSql(originalSql);

        return "SELECT COUNT(*) FROM (" + baseSql + whereClause + ") temp_count_table";
    }


    /**
     * 获取基础SQL（移除可能的WHERE和ORDER BY）
     */
    private static String getBaseSql(String sql) {
        String upperSql = sql.toUpperCase();
        int whereIndex = upperSql.indexOf(" WHERE ");
        int orderIndex = upperSql.indexOf(" ORDER BY ");

        if (whereIndex != -1) {
            return sql.substring(0, whereIndex);
        } else if (orderIndex != -1) {
            return sql.substring(0, orderIndex);
        } else {
            return sql;
        }
    }

    /**
     * 构建分页子句
     */
    private static String buildLimitClause(Map<String, Object> params) {
        if (params == null || !params.containsKey("pageNo") || !params.containsKey("pageSize")
                || params.get("pageNo") == null || params.get("pageSize") == null) {
            return "";
        }
        int pageNo = Integer.parseInt(params.get("pageNo").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());

        if (pageNo > 0 && pageSize > 0) {
            int offset = (pageNo - 1) * pageSize;
            return " LIMIT " + offset + "," + pageSize;
        }

        return "";
    }
    /**
     * 构建排序子句
     */
    private static String buildOrderClause(Map<String, Object> params) {
        if (params == null || !params.containsKey("sortBy")) {
            return "";
        }

        String sortBy = (String) params.get("sortBy");
        String sortOrder = params.containsKey("sortOrder") ?
                (String) params.get("sortOrder") : "ASC";

        if (sortBy != null && !sortBy.trim().isEmpty()) {
            return " ORDER BY " + sortBy + " " + sortOrder;
        }

        return "";
    }




    /**
     * 构建IN子句
     */
    private static String buildInClause(Object value) {
        if (value instanceof Collection) {
            Collection<?> collection = (Collection<?>) value;
            return collection.stream()
                    .map(DynamicSqlProvider::formatValue)
                    .collect(Collectors.joining(", "));
        } else if (value instanceof Object[]) {
            Object[] array = (Object[]) value;
            return Arrays.stream(array)
                    .map(DynamicSqlProvider::formatValue)
                    .collect(Collectors.joining(", "));
        } else {
            return formatValue(value);
        }
    }

    /**
     * SQL转义 - 防止SQL注入
     */
    private static String escapeSql(String value) {
        if (value == null) return "";
        return value.replace("'", "''")
                .replace("\\", "\\\\")
                .replace("\"", "\\\"");
    }


    /**
     * 构建BETWEEN子句
     */
    private static String buildBetweenClause(Object value) {
        if (value instanceof Object[] && ((Object[]) value).length == 2) {
            Object[] range = (Object[]) value;
            return formatValue(range[0]) + " AND " + formatValue(range[1]);
        } else {
            throw new IllegalArgumentException("BETWEEN查询需要两个值的数组");
        }
    }

}
